<?php
namespace app\queue\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Cache;
use think\facade\Queue;
use think\queue\Job;
use think\facade\Db;
use think\facade\Log;
 use app\queue\model\Order as orderModel;
 

class Order extends BaseController
{
  
    public $appkey = "24621156";
    public $secretKey = "0bb03f8580bee64c5a03e50a67f3e222";

    private static $config = [ // 列队映射关系
        'orderTb'=> [// 同步一个月淘宝订单列队
            'name'=> 'YueOrder',
            'class'=> 'app\job\Order@order_tb',
        ]
    ];

    public function o_test(){
                 echo Cache::set('queue_num','101');



        die;
    }
        /**
     * [publish 发布列队]
     * @param  string      $name [列队名称]
     * @param  string      $data [推送数据]
     * @param  string      $wait [延迟推送]
     * @return [type]            [description]
     */
    public static function publish(string $name, $data = '', $wait = '')
    {


        if (!isset(self::$config[$name])) return false; // 没有对应的映射关系
        $jobData = self::$config[$name];
        $result = $wait ? Queue::push($jobData['class'], $data, $jobData['name']) : Queue::later($wait, $jobData['class'], $data, $jobData['name']);
   
        if ($result === false) {

            write_log('error-订单列队推送失败数据-列队名称:'.$jobData['name'],$data,'publish');
        }
        return $result;
    }
 

      /**
       * fire方法是消息队列默认调用的方法
       * @param Job            $job      当前的任务对象
       * @param array|mixed    $data     发布任务时自定义的数据
       */
      public function order_tb(Job $job,$data)
      {

        
        
      	  
          // 有些消息在到达消费者时,可能已经不再需要执行了
           $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
          if(!$isJobStillNeedToBeDone){
              $job->delete();
              return;
          }
          $isJobDone = $this->doHelloJob($data);
          if ($isJobDone) {
              $job->delete();
              // print("<info>Hello Job has been done and deleted"."</info>\n");
          }else{
           
    
              if ($job->attempts() > 3) {
                $job->delete();

                write_log('error-执行列队3次以上失败-',$data,'order_tb');
      
                  // print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");
    				    
                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
               //$delay为延迟时间，表示该任务延迟2秒后再执行
              }
          }
      }
      
      /**
       * 有些消息在到达消费者时,可能已经不再需要执行了
       * @param array|mixed    $data     发布任务时自定义的数据
       * @return boolean                 任务执行的结果
       */
      private function checkDatabaseToSeeIfJobNeedToBeDone($data){
          return true;
      }

      




      /**
       * 根据消息中的数据进行实际的业务处理...
       */
      private function doHelloJob($data) 
      {

 
 
        // $return_json = $orderModel->get_order($data);
        // Db::name('test')->insert(array('test'=>json_encode($return_json)));
        try {
          $orderModel = new orderModel();
          $start_time  = $data['start_time'];
          $end_time = $data['end_time'];
          // while( $start_time<$end_time){
              // page_no 页数
              // position_index 分页点位
              $return_json = $orderModel->get_order($data);
              if($return_json['status']==1){

                // 数据库操作 添加或更新数据
                $orderModel->orderUpdate($return_json['data']);
                // //表示是否还有下一页true 有，false 无
                if($return_json['has_next']=='true'){
                    $data['page_no'] = $data['page_no']+1;
                    $data['position_index']=$return_json['position_index'];
                    
                   self::publish($data['queName'],$data,1);
                   

                }
              };
              // $start_time = $start_time+1200;
          // }
        } catch (\Exception $e) {
 

            write_log('error-订单列队操作失败-'.$e->getMessage().'-'.$e->getline(),$data,'doHelloJob');
            return false;
        }
        return true;
      }

   
}
